const chalk = require('chalk');
const urllib = require('url')
const moment = require('moment')
const querystring = require("querystring")
import cloneDeep from 'lodash/cloneDeep'
const log4js = require('log4js');
const path = require('path')
const fs = require('fs')
const rootPath = process.cwd()
import { LOG_PATH } from '../config'

const getNowTime = () => {
  return moment().format()
}

const rangeArray = (n) => {
  return n <= 0 ? [] : [...new Array(n).keys()]
}
const getBlobPageQuery = (keyword, page) => {
  const baseUrl = 'https://m.weibo.cn/api/container/getIndex'
  const options = {
    containerid: querystring.escape('100103type=1&q=' + keyword),
    page: page,
    page_type: 'searchall'
  }
  return baseUrl + '?' + querystring.stringify(options)
}
const getCommentPageQuery = (comId, page) => {
  const baseUrl = 'https://m.weibo.cn/api/comments/show'
  const options = {
    id: comId,
    page: page
  }
  return baseUrl + '?' + querystring.stringify(options)
 }
const formatTime = (timestamp, type = 'line') => {
  var y, m, d, h, mm, s
  var t = new Date(timestamp)
  y = t.getFullYear()
  m = setZero(t.getMonth() + 1)
  d = setZero(t.getDate())
  h = setZero(t.getHours())
  mm = setZero(t.getMinutes())
  s = setZero(t.getSeconds())
  if (type === 'line') {
    return y + '-' + m + '-' + d + '-' + h + '-' + mm + '-' + s
  } else if (type === 'point') {
    return y + '.' + m + '.' + d + ' ' + h + ':' + mm + ':' + s
  }
}
const setZero = (n) => {
  return n < 10 ? ('0' + n) : n
}
const formatDiff = (_diff) => {
  var diff = parseInt(_diff / 1000 + '', 10)
  var d, h, m, s, ds = 24 * 60 * 60, hs = 60 * 60,
    ms = 60, ss = 1
  d = parseInt(diff / ds + '', 10)
  diff = diff - d * ds
  h = parseInt(diff / hs + '', 10)
  diff = diff - h * hs
  m = parseInt(diff / ms + '', 10)
  diff = diff - m * ms
  s = parseInt(diff / ss + '', 10)
  d = (d > 0) ? (d + '天 ') : ''
  h = setZero(h)
  m = setZero(m)
  s = setZero(s)
  return d + h + ':' + m + ':' + s
}

class Log {
  constructor() {
    this.logger = null
  }
  createLogFile(realPath) {
    return new Promise((resolve, reject) => {
      fs.open(realPath, 'w', (res) => {
        console.log('res', res)
        console.log('realpath', realPath)
        resolve()
      })
    })
  }
  async initLoger(taskId, keyword) {
    if (!fs.existsSync(LOG_PATH)) {
      fs.mkdirSync(LOG_PATH)
    }
    const filename = formatTime(Date.now()) + '_' + taskId + '_' + keyword + '.log'
    const realPath = path.join(LOG_PATH, filename)
    await this.createLogFile(realPath)
    log4js.configure({
      appenders: {
        ruleFile: {
          type: 'file',
          filename: realPath
        }
      },
      categories: {
        default: {
          appenders: ['ruleFile'],
          level: 'all'
        }
      }
    })
    this.logger = log4js.getLogger('ruleFile')
  }
  addLog(msg, type) {
    if (type === 'info') {
      this.logger.info(msg)
    } else if (type === 'error') {
      this.logger.error(msg)
    } else if (type === 'success') {
      this.logger.info(msg)
    } else if (type === 'warn') {
      this.logger.warn(msg)
    } else if (type === 'debug') {
      this.logger.debug(msg)
    }
  }
  log() {
    console.log.apply(console, arguments)
    this.addLog(Object.values(arguments).join('--'), 'info')
  }
  logError() {
    const error = chalk.bold.red
    Object.keys(arguments).map((_) => {
      arguments[_] = typeof arguments[_] === 'object' ? JSON.stringify(arguments[_]) : arguments[_]
    })
    console.log(error.apply(chalk, arguments))
    this.addLog(Object.values(arguments).join('--'), 'error')
  }
  logWarn() {
    const warn = chalk.keyword('orange')
    Object.keys(arguments).map((_) => {
      arguments[_] = typeof arguments[_] === 'object' ? JSON.stringify(arguments[_]) : arguments[_]
    })
    console.log(warn.apply(chalk, arguments))
    this.addLog(Object.values(arguments).join('--'), 'warn')
  }
  logSuccess() {
    const green = chalk.green
    Object.keys(arguments).map((_) => {
      arguments[_] = typeof arguments[_] === 'object' ? JSON.stringify(arguments[_]) : arguments[_]
    })
    console.log(green.apply(chalk, arguments))
    this.addLog(Object.values(arguments).join('--'), 'success')
  }
  logDebug() {
    const green = chalk.blue
    Object.keys(arguments).map((_) => {
      arguments[_] = typeof arguments[_] === 'object' ? JSON.stringify(arguments[_]) : arguments[_]
    })
    console.log(green.apply(chalk, arguments))
    this.addLog(Object.values(arguments).join('--'), 'debug')
  }
}

export {
  rangeArray,
  urllib,
  querystring,
  getBlobPageQuery,
  getCommentPageQuery,
  Log,
  cloneDeep,
  formatTime,
  rootPath,
  formatDiff,
  getNowTime
}
